package com.juzhencms.apps.busi.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.juzhencms.apps.base.common.database.DBTable;
import com.juzhencms.apps.base.common.util.ObjectUtil;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class RoleService extends CommonService{
	
	@Autowired
	private AdminMenuService adminMenuService;
	
	@Autowired
	private UserService userService;
	
	public Map getRoleEditPermissionData(List roleValueList) {
		//避免覆盖全局数据，采用复制方式
		Map permissionsData=ObjectUtil.copy(adminMenuService.getPermissionsData(),Map.class);
		
		Map modulePermissions=(Map)permissionsData.get("modulePermissions");
		
		/*//获取全部站点
		List siteMenuTreeList=adminMenuService.getAllSiteMenuTreeList();
		
		//根据当前用户的机构筛选出可以显示的站点信息
		String siteIdStr=userService.getLoginUser().getSiteIds();
		if(siteIdStr!=null) {
			List newSiteMenuTreeList=new ArrayList();
			//在这里根据机构ID获取机构下的站点进行筛选
			if(siteMenuTreeList!=null) {
				for(int i=0;i<siteMenuTreeList.size();i++) {
					Map site=(Map)siteMenuTreeList.get(i);
					Pattern p=Pattern.compile("(^|.+,)"+site.get("id")+"(,.+|$)",Pattern.CASE_INSENSITIVE);//第二个参数代表不区分大小写,可以同时使用多种，例如 Pattern.CASE_INSENSITIVE | Pattern.MULTILINE
					Matcher m=p.matcher(siteIdStr);
					if(m.matches()) {
						newSiteMenuTreeList.add(site);
					}
				}
				siteMenuTreeList=newSiteMenuTreeList;
			}
		}*/
		
		//根据当前用户的机构筛选出可以显示的站点信息
		String siteIdStr=userService.getLoginUser().getSiteIds();
		//改进方案，只查询有权限的站点
		List siteMenuTreeList=adminMenuService.getSiteMenuTreeList(siteIdStr);
		
		
		
		
		Map content=(Map)modulePermissions.get("content");
		content.put("sub", siteMenuTreeList);
		content.put("open", true);
		
		//角色编辑下不需要显示演示组件部分
		modulePermissions.remove("exampleModules");
		
		//改进算法，根据当前用户的权限范围显示菜单数据
		Map userPermissions=userService.getLoginUser().getPermissions();
		//过滤actions数据，设置已设定的权限聚焦
		if(userPermissions!=null && userPermissions.get("root")==null){
			//改进方法，根基自身权限显示可用的权限范围
			this.makeModulePermissionTreeDataByLoginUserPermissions(modulePermissions,roleValueList);
		}else {
			//如果是超级管理员则展示全部菜单
			this.makeModulePermissionTreeData(modulePermissions,roleValueList);
		}
		
		
		
		return modulePermissions;
	}
	
	/**
	 * 处理编辑角色时的权限数组
	 * @param data
	 * @param roleValueList
	 */
	private void makeModulePermissionTreeData(Map data,List roleValueList){
		if(data!=null){
			for (Map moduleMenuData : ((Map<String,Map>)data).values()) {

				if(roleValueList.contains(moduleMenuData.get("module"))){
					moduleMenuData.put("checked", true);
				}
				
				if(moduleMenuData.get("sub")!=null){
					this.makeModulePermissionTreeData((List)moduleMenuData.get("sub"),roleValueList);
				}	
			}
		}
	}
	
	//改进方法，根基自身权限显示可用的权限范围
	private void makeModulePermissionTreeDataByLoginUserPermissions(Map data,List roleValueList){
		
		//查询当前用户的角色和权限范围
		int loginUserId=userService.getLoginUser().getId();
		Map userData=this.getJdbcDao().queryRow("select id,role from "+DBTable.user+" where id=?", new Object[] {loginUserId});
		List loginUserPermissionList=new ArrayList();
		
		
		if(userData!=null && userData.get("role")!=null) {
			String loginUserRole=userData.get("role").toString();
			
			Matcher roleMatcher = Pattern.compile("^,(.*),$").matcher(loginUserRole);
			if(roleMatcher.find()){
				loginUserRole=roleMatcher.replaceAll("$1");
				List loginUserRoleList=this.getJdbcDao().querySql("select permission from "+DBTable.role+" where id in ("+loginUserRole+") and publish=1 and del_flag=0");
				if(loginUserRoleList!=null && loginUserRoleList.size()>0) {
					for(int i=0;i<loginUserRoleList.size();i++) {
						Map tmpRole=(Map)loginUserRoleList.get(i);
						if(tmpRole.get("permission")!=null && !tmpRole.get("permission").toString().equals("")) {
							loginUserPermissionList.addAll(Arrays.asList(tmpRole.get("permission").toString().split(",")));
						}
					}
				}				
			}
		}
		
		
		//log.info(JSON.toJSONString(data));
		//log.info(JSON.toJSONString(loginUserPermissionList));
		
		if(data!=null){
			
			Set keys=data.keySet();
			Iterator<String> it = keys.iterator();
			while(it.hasNext()){
				String key =it.next();
				
				
				//-------------------------------------------
				Map moduleMenuData=(Map)data.get(key);
				
				
				if(!loginUserPermissionList.contains(moduleMenuData.get("module"))){
					it.remove();
				}

				if(roleValueList.contains(moduleMenuData.get("module"))){
					moduleMenuData.put("checked", true);
				}
				
				

				
				if(moduleMenuData.get("sub")!=null){
					//改进部分，对栏目权限不进行过滤删除，方便管理新增加的栏目，直接使用超级管理员的这个方法即可
					if(key.equals("content")) {
						this.makeModulePermissionTreeData((List)moduleMenuData.get("sub"),roleValueList);
					}else {
						this.makeModulePermissionTreeDataByLoginUserPermissions((List)moduleMenuData.get("sub"),roleValueList,loginUserPermissionList);
					}
				}	
			}
		}
	}
	
	/**
	 * 处理编辑角色时的权限数组
	 * @param data
	 * @param roleValueList
	 */
	private void makeModulePermissionTreeData(List data,List roleValueList){
		if(data!=null){
			for (int i=0;i<data.size();i++) {
				Map moduleMenuData=(Map)data.get(i);
				
				if(roleValueList.contains(moduleMenuData.get("module"))){
					moduleMenuData.put("checked", true);
				}
				
				moduleMenuData.remove("actions");
				moduleMenuData.remove("link");
				List subOptions=null;
				List subModule=null;
				if(moduleMenuData.get("options")!=null){
					subOptions=(List)moduleMenuData.get("options");
					for(int j=0;j<subOptions.size();j++){
						Map option=(Map)subOptions.get(j);
						option.put("module", moduleMenuData.get("module")+"."+option.get("option"));
						//添加自定义图标
						option.put("icon", "assets/global/plugins/jquery.ztree/img/diy/2.png");
						option.remove("option");
					}
					
					
					moduleMenuData.remove("options"); 
				}
				
				if(moduleMenuData.get("sub")!=null){
					subModule=(List)moduleMenuData.get("sub");	
				}
				
				if(subOptions==null)
					subOptions=new ArrayList();
				
				if(subModule==null)
					subModule=new ArrayList();
				
				subOptions.addAll(subModule);
				
				if(subOptions.size()>0)
					moduleMenuData.put("sub", subOptions);
				
				this.makeModulePermissionTreeData(subOptions,roleValueList);
			}
		}
	}
	
	/**
	 * 处理编辑角色时的权限数组
	 * @param data
	 * @param roleValueList
	 */
	private void makeModulePermissionTreeDataByLoginUserPermissions(List data,List roleValueList,List loginUserPermissionList){
		if(data!=null){
			Iterator<Map> it = data.iterator();
			while(it.hasNext()){
				Map moduleMenuData = it.next();
				
				if(!loginUserPermissionList.contains(moduleMenuData.get("module"))){
					it.remove();
				}
				
				//log.info(moduleMenuData.get("module").toString());
				
				if(roleValueList.contains(moduleMenuData.get("module"))){
					moduleMenuData.put("checked", true);
				}
				
				moduleMenuData.remove("actions");
				moduleMenuData.remove("link");
				List subOptions=null;
				List subModule=null;
				if(moduleMenuData.get("options")!=null){
					subOptions=(List)moduleMenuData.get("options");
					for(int j=0;j<subOptions.size();j++){
						Map option=(Map)subOptions.get(j);
						option.put("module", moduleMenuData.get("module")+"."+option.get("option"));
						//添加自定义图标
						option.put("icon", "assets/global/plugins/jquery.ztree/img/diy/2.png");
						option.remove("option");
					}
					
					
					moduleMenuData.remove("options"); 
				}
				
				if(moduleMenuData.get("sub")!=null){
					subModule=(List)moduleMenuData.get("sub");	
				}
				
				if(subOptions==null)
					subOptions=new ArrayList();
				
				if(subModule==null)
					subModule=new ArrayList();
				
				subOptions.addAll(subModule);
				
				if(subOptions.size()>0)
					moduleMenuData.put("sub", subOptions);
				
				
				this.makeModulePermissionTreeDataByLoginUserPermissions(subOptions,roleValueList,loginUserPermissionList);
			}
		}
	}

	
	
	/*
	 * getLists：获取(受机构限制)角色列表
	 * @param fields 查询字段默认
	 * @param where String 条件，比如：name like ?
	 * @param whereParamList list 条件参数，如：List whereParamList=new ArrayList();whereParamList.add("%金先生%");
	 * @param orderBy 排序 默认 order by position asc,id asc
	 * @param pageIndex 页码
	 * @param pageSize 每页页数 使用时需与pageIndex都设置 
	 * @param is_not_limit_org 不设置机构限制 默认0设置 1不设置
	 * @return list
	 * 应用：siteService.getAllSite(null, null, null, null, 0, 0);
	 */
	public List getLists(String fields, String where, List whereParamList, String orderBy, int pageIndex,
			int pageSize,int is_not_limit_org) {

		// 查询字段
		if (fields == null || fields.equals("")) {
			fields = " * ";
		}

		// 查询条件
		String setWhere = "  where  1=1  ";
		if (where != null && !where.equals("")) {
			setWhere += " and "+where;
		}
		
		//机构限制：系统管理员、超级管理员以外的管理员用户都需要加机构限制
		if(is_not_limit_org == 0){
			String getLoginUserOrgIds = userService.getLoginUser().getSubOrgIds();
			setWhere += " and org_id in ("+getLoginUserOrgIds+") ";
			
		}

		// 排序：默认ID倒序
		if (orderBy == null || orderBy.equals("")) {
			orderBy = " order by position asc,id asc";
		}

		// 页码，0代表全显示
		String setLimit = "";
		if (pageIndex > 0 && pageSize > 0) {
			setLimit = " limit ?,? ";
			//
			int start=0;
			if(pageIndex>1){
				start=(pageIndex-1)*pageSize;
			}
			whereParamList.add(start);
			whereParamList.add(pageSize);
		}

		// 语句
		String sql = "select " + fields + " from " + DBTable.role + setWhere + orderBy + setLimit;

		// 参数条件
		List dataList = null;
		if (whereParamList != null && whereParamList.size() > 0) {
			dataList = this.getJdbcDao().querySql(sql, whereParamList.toArray());
		} else {
			dataList = this.getJdbcDao().querySql(sql);
		}
		return dataList;

	}
	
	/*
	 * 获取(受机构限制)角色列表
	 */
	public List getLists(String fields) {
		// 查询字段
		if (fields == null || fields.equals("")) {
			fields = " * ";
		}
		return this.getLists(fields, null, null, null, 0, 0,0);
	}
	
	/*
	 * getDetail：获取（机构限制）指定角色信息
	 * @param fields 查询字段默认
	 * @param where String 条件，比如：name like ?
	 * @param whereParamList list 条件参数，如：List whereParamList=new ArrayList();whereParamList.add("%金先生%");
	 * @param orderBy String 排序
	 * @param is_not_limit_org 不设置机构限制 默认0设置 1不设置
	 * @return Map
	 */
	public Map getDetail(String fields, String where, List whereParamList,String orderBy,int is_not_limit_org ) {
		
		// 查询字段
		if (fields == null || fields.equals("")) {
			fields = " * ";
		}

		// 查询条件
		String setWhere = "  where  1=1  ";
		if (where != null && !where.equals("")) {
			setWhere += " and "+where;
		}
		
		//机构限制：系统管理员、超级管理员以外的管理员用户都需要加机构限制
		if(is_not_limit_org == 0) {
			String getLoginUserOrgIds = userService.getLoginUser().getSubOrgIds();
			setWhere += " and org_id in ("+getLoginUserOrgIds+") ";
			
		}

		// 排序：默认ID倒序
		if (orderBy == null) {
			orderBy = " order by position asc,id asc";
		}

		// 仅查询一条
		String setLimit = " limit 1 ";
		
		// 语句
		String sql = "select " + fields + " from " + DBTable.role + setWhere + orderBy + setLimit;

		// 参数条件
		Map data = new HashMap();
		if (whereParamList != null && whereParamList.size() > 0) {
			data =  this.getJdbcDao().queryRow(sql,whereParamList.toArray());	
		} else {
			data =  this.getJdbcDao().queryRow(sql);	
		}
		return data;
	}
	
	/*
	 * getDetail：获取（机构限制）指定角色信息
	 */
	public Map getDetail(int id,String fields) {
		if(id<=0) {
			return null;
		}
		String where = " id =  "+id;
		return this.getDetail(fields, where,null,null,0);
	}
	

}
